package model

import (
	"encoding/json"
	"fmt"
	"im/libs"
)

type User struct {
	conn *libs.Database
}

type Msg struct {
	Uid  uint64
	Text string
}

func NewChat(redis *libs.Redis) (*Chat, error) {
	conn := libs.NewRedisConn(redis)
	r := &Chat{conn: conn}
	return r, nil
}

func (c *Chat) SendToUser(fromuid, touid uint64, msg string) error {
	m := Msg{Uid: fromuid, Text: msg}
	key := fmt.Sprintf("m_%d", touid)
	mb, e := json.Marshal(m)
	if e != nil {
		return e
	}
	e = c.conn.RPush(key, mb).Err()
	if e != nil {
		return e
	}
	return nil
}

func (c *Chat) RecvUser(touid uint64) (*Msg, error) {
	m := &Msg{}
	key := fmt.Sprintf("m_%d", touid)

	mb, e := c.conn.LPop(key).Bytes()
	if e != nil {
		return nil, e
	}
	e = json.Unmarshal(mb, m)
	if e != nil {
		return nil, e
	}
	return m, nil
}
